<?php
// +----------------------------------------------------------------------
// | 授权系统 - 验证日志控制器
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\license;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use common\models\system\LicenseLog;
use yii\db\ActiveQuery;

/**
 * 验证日志控制器
 */
class LogController extends AuthController
{
    use CommonAction;
    
    protected string $model = LicenseLog::class;
    protected bool $validate = false;
    
    protected function listQuery(ActiveQuery $query): ActiveQuery
    {
        return $query->with(['license'])->orderBy(['id' => SORT_DESC]);
    }
    
    protected function listAfter(array $list): array
    {
        // 格式化数据
        foreach ($list as $key => &$item) {
            $item['validate_result_text'] = $item['validate_result'] ? '成功' : '失败';
            $item['validate_type_text'] = $item['validate_type'] == 'online' ? '在线' : '离线';
            $item['is_abnormal_text'] = $item['is_abnormal'] ? '是' : '否';
        }
        return $list;
    }
    
    /**
     * 统计数据
     */
    public function actionStatistics()
    {
        $params = $this->request->get();
        
        // 今日统计
        $todayStart = date('Y-m-d 00:00:00');
        $todayStats = [
            'total' => LicenseLog::find()->where(['>=', 'created_at', $todayStart])->count(),
            'success' => LicenseLog::find()->where(['>=', 'created_at', $todayStart])->andWhere(['validate_result' => 1])->count(),
            'fail' => LicenseLog::find()->where(['>=', 'created_at', $todayStart])->andWhere(['validate_result' => 0])->count(),
            'abnormal' => LicenseLog::find()->where(['>=', 'created_at', $todayStart])->andWhere(['is_abnormal' => 1])->count(),
        ];
        
        // 本月统计
        $monthStart = date('Y-m-01 00:00:00');
        $monthStats = [
            'total' => LicenseLog::find()->where(['>=', 'created_at', $monthStart])->count(),
            'success' => LicenseLog::find()->where(['>=', 'created_at', $monthStart])->andWhere(['validate_result' => 1])->count(),
            'fail' => LicenseLog::find()->where(['>=', 'created_at', $monthStart])->andWhere(['validate_result' => 0])->count(),
            'abnormal' => LicenseLog::find()->where(['>=', 'created_at', $monthStart])->andWhere(['is_abnormal' => 1])->count(),
        ];
        
        // 最近7天趋势
        $trendData = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $dayStart = $date . ' 00:00:00';
            $dayEnd = $date . ' 23:59:59';
            
            $trendData[] = [
                'date' => $date,
                'total' => LicenseLog::find()->where(['>=', 'created_at', $dayStart])->andWhere(['<=', 'created_at', $dayEnd])->count(),
                'success' => LicenseLog::find()->where(['>=', 'created_at', $dayStart])->andWhere(['<=', 'created_at', $dayEnd])->andWhere(['validate_result' => 1])->count(),
                'fail' => LicenseLog::find()->where(['>=', 'created_at', $dayStart])->andWhere(['<=', 'created_at', $dayEnd])->andWhere(['validate_result' => 0])->count(),
            ];
        }
        
        // 错误类型统计（最近30天）
        $thirtyDaysAgo = date('Y-m-d H:i:s', strtotime('-30 days'));
        $errorStats = LicenseLog::find()
            ->select(['error_code', 'COUNT(*) as count'])
            ->where(['>=', 'created_at', $thirtyDaysAgo])
            ->andWhere(['validate_result' => 0])
            ->andWhere(['IS NOT', 'error_code', null])
            ->groupBy('error_code')
            ->asArray()
            ->all();
        
        return $this->success('', [
            'today' => $todayStats,
            'month' => $monthStats,
            'trend' => $trendData,
            'errors' => $errorStats,
        ]);
    }
}
